const BaseRest = require('./base.js');

module.exports = class extends BaseRest {
  // 查询用户信息
  async getAction() {
    const userInfo = this.userInfo;
    if (think.isEmpty(userInfo)) {
      this.ctx.status = 401;
      return this.fail(-1, '请登录后操作');
    }
    
    let data;
    
    if (this.id) {
      // 根据ID查附加信息
      if (this.get('member')) {
        data = await this.model('user_member').where({
          uid: this.id,
        }).find();

        return this.success(data);
      } else {
        data = await this.modelInstance.where({
          id: this.id,
        }).fieldReverse('password,encrypt').find();
        // 头像改成内置的图像管理工具管理
        if (!think.isEmpty(data)) {
          if (data['avator_id']) {
            data.avator = this.model('image').getFullPath(data['avator_id']);
          } else {
            // 默认头像
            data.avator = 'https://secure.gravatar.com/avatar/' +
                think.md5(data.email);
          }
          delete data['avator_id'];
          
          data['roles'] = await this.modelInstance.getRoles(data.id);
          data['tags'] = await this.modelInstance.getTags(data.id);
        }
        return this.success(data);
      }
    }
    
    // 根据username查询
    if (this.get('username')) {
      data = await this.modelInstance.where({
        username: this.get('username'),
      }).fieldReverse('password,encrypt').find();
      if (!think.isEmpty(data)) {
        // data.avator = 'https://secure.gravatar.com/avatar/' +
        // think.md5(data.email);
        if (data['avator_id']) {
          data.avator = this.model('image').getFullPath(data['avator_id']);
        } else {
          // 默认头像
          data.avator = 'https://secure.gravatar.com/avatar/' +
              think.md5(data.email);
        }
        delete data['avator_id'];
      }
      
      return this.success(data);
    }
    
    // 分页查找
    const map = {};
    // 页码
    const page = this.get('page') || 1;
    // 每页显示数量
    const pageSize = this.get('pageSize') || 5;
    
    // 关键词
    const key = this.get('key');
    if (key) {
      map['username|email|mobile'] = ['like', '%' + key + '%'];
    }
    
    if (this.get('role_id')) {
      map['r.id'] = this.get('role_id');
      data = await this.modelInstance.alias('u').
      join({
        table: 'user_role', join: 'left', as: 'ur', on: ['u.id', 'ur.uid'],
      }).
      join({
        table: 'role', join: 'left', as: 'r', on: ['ur.role_id', 'r.id'],
      }).
      where(map).
      page(page, pageSize).
      order('deleted_flag asc, last_login_time desc').
      fieldReverse('password,encrypt').
      countSelect();
      
      // await data.data.forEach(async element => {
      //     // if (element['avator_id']) {
      //     //     element.avator = await
      // this.model('image').getFullPath(element['avator_id']); // } else { //
      //    //默认头像 //     element.avator =
      // 'https://secure.gravatar.com/avatar/' + think.md5(element.email); // }
      // // delete element['avator_id'];   let roles = await
      // this.modelInstance.getRoles(element.id); element['roles'] =roles; });
      
      for (const element of data.data) {
        if (element['avator_id']) {
          element.avator = await this.model('image').getFullPath(element['avator_id']);
        } else {
          // 默认头像
          element.avator = 'https://secure.gravatar.com/avatar/' +
              think.md5(element.email);
        }
        delete element['avator_id'];
        
        element['roles'] = await this.modelInstance.getRoles(element.id);
        element['tags'] = await this.modelInstance.getTags(element.id);
      }
      return this.success(data);
    }
    
    data = await this.modelInstance.where(map).
    page(page, pageSize).
    order('deleted_flag asc, last_login_time desc').
    fieldReverse('password,encrypt').
    countSelect();
    // await data.data.forEach(async element => {
    //     //头像需要根据avator_id生成
    //
    //     // if (element['avator_id']) {
    //     //     element.avator = await
    // this.model('image').getFullPath(element['avator_id']); // } else { //
    //  //默认头像 //     element.avator = 'https://secure.gravatar.com/avatar/' +
    // think.md5(element.email); // } // delete element['avator_id'];  let
    // roles = await this.modelInstance.getRoles(element.id); element.roles =
    // roles; });
    
    for (const element of data.data) {
      if (element['avator_id']) {
        element.avator = await this.model('image').
        getFullPath(element['avator_id']);
      } else {
        // 默认头像
        element.avator = 'https://secure.gravatar.com/avatar/' +
            think.md5(element.email);
      }
      delete element['avator_id'];
      
      element['roles'] = await this.modelInstance.getRoles(element.id);
      element['tags'] = await this.modelInstance.getTags(element.id);
    }
    
    return this.success(data);
  }
  
  async postAction() {
    const data = this.post();
    
    // 添加标签
    if (this.post('tag') && this.post('uid')) {
      const tag = await this.model('user_tag').where({
        title: this.post('tag'),
      }).find();
      
      let tagId;
      if (think.isEmpty(tag)) {
        tagId = await this.model('user_tag').add({
          title: this.post('tag'),
        });
      } else {
        tagId = tag.id;
      }
      
      if (tagId) {
        const id = await this.model('user').addTag(this.post('uid'), tagId);
        if (id) {
          return this.success({id: id}, '添加成功');
        } else {
          return this.fail(1000, '添加失败');
        }
      } else {
        return this.fail(1000, '添加失败');
      }
    }
    
    // 用户注册
    const user = await this.modelInstance.where({
      username: data['username'],
    }).find();
    if (!think.isEmpty(user)) {
      return this.fail(-1, '用户名已经存在');
    }
    
    data['encrypt'] = think.service('utils').getRamdomString(10, {});
    data['password'] = think.service('utils').
    getEncryptPassword(data['password'], data['encrypt']);
    data['create_ip'] = this.ctx.ip;
    data['create_time'] = Math.round((new Date()).getTime() / 1000);
    const ret = await this.modelInstance.addUser(data);
    
    // think.logger.debug(ret);
    return this.success(ret);
  }
  
  // 更新用户信息
  async putAction() {
    // 删除缓存
    think.cache('user', null);
    const data = this.post();
    if (think.isEmpty(data)) {
      return this.fail(1000, '数据不能为空');
    }
    
    // think.logger.debug(data);
    
    if (this.get('member')) {
      const rows = await this.model('user_member').where({
        uid: this.id,
      }).update(data);
      if (rows) {
        return this.success({
          affectedRows: rows,
        }, '更新成功');
      } else {
        return this.fail(1000, '更新失败');
      }
    } else {
      delete (data['avator']);
      delete (data['login_count']);
      delete (data['last_login_ip']);
      delete (data['last_login_time']);
      delete (data['create_ip']);
      delete (data['create_time']);
      delete (data['login_fail_count']);
      // delete(data['deleted_flag']);
      
      think.logger.debug(data);
      
      if (!think.isEmpty(data['password'])) {
        data['encrypt'] = think.service('utils').getRamdomString(10, {});
        data['password'] = think.service('utils').
        getEncryptPassword(data['password'], data['encrypt']);
      } else {
        delete (data['password']);
      }
      
      const rows = await this.modelInstance.where({
        id: this.id,
      }).update(data);
      if (rows) {
        return this.success({
          affectedRows: rows,
        }, '更新成功');
      } else {
        return this.fail(1000, '更新失败');
      }
    }
  }
  
  /**
   * 删除内容
   * @return {[type]} [description]
   */
  async deleteAction() {
    if (!this.id) {
      return this.fail(1001, '用户不存在');
    }
    
    if (this.get('tag_id')) {
      const rows = await this.model('user').
      deleteTag(this.id, this.get('tag_id'));
      if (rows) {
        return this.success({
          affectedRows: rows,
        }, '删除成功');
      } else {
        return this.fail(1000, '删除失败');
      }
    }
    
    // 软删除标志
    // 不允许删除系统账号
    
    const map = {
      id: this.id, username: ['NOTIN', ['root', 'admin']],
    };
    const rows = await this.modelInstance.where(map).update({
      deleted_flag: 1,
    });
    if (rows) {
      await this.hook('userDelete', {
        id: this.id,
      });
      return this.success({
        affectedRows: rows,
      }, '删除成功');
    } else {
      return this.fail(1000, '删除失败');
    }
  }
};
